package com.example.oauth2.service;


import com.example.oauth2.entry.User;
import com.example.oauth2.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 自定义UserDetailsService类
 */
@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        Optional<User> opt = Optional.ofNullable(userRepository.findByUserName(userName));

        if (opt.isPresent()) {
            User user = opt.get();
            return new CustomUserDetails(user.getUserName(), user.getPassword(), user.getRoles());
        }

        throw new UsernameNotFoundException(userName);

    }
}
